package com.frontop.terminal.rmonclient.util;

import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;

/**
 * @author matrixy
 * @date 2017-02-23
 */
public final class Log {
    private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final OutputStream LOG_WRITER = System.err;

    private static synchronized String getCurrentTime() {
        return SDF.format(new java.util.Date());
    }

    private static byte[] toBytes(String message, Type type) {
        try {
            return (getCurrentTime() + " " + type + ": " + message).getBytes(StandardCharsets.UTF_8);
        } catch (Exception e) {
            // ..
        }
        return new byte[0];
    }

    public static void error(Throwable ex) {
        try {
            ex.printStackTrace();
            LOG_WRITER.write(toBytes(ex.toString(), Type.ERROR));
            LOG_WRITER.write('\n');
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void info(String message) {
        try {
            LOG_WRITER.write(toBytes(message, Type.INFO));
            LOG_WRITER.write('\n');
        } catch (Exception ignored) {
        }
    }


    private enum Type {
        /**
         * ERROR/INFO
         */
        ERROR,

        /**
         * ERROR/INFO
         */
        INFO,
        /**
         * ERROR/INFO
         */
        @SuppressWarnings("unused") DEBUG
    }
}
